package net.mihome.app.ui;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.adapter.SimpleSpinnerAdapter;
import net.mihome.app.bean.Community;
import net.mihome.app.bean.CommunityList;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;
import net.mihome.app.widget.LoadingDialog;

import org.apache.http.Header;

import java.util.List;
import java.util.Map;

public class RegisterCommnuity extends BaseActivity {
	private EditText commnuitySpinner;
	private EditText buildSpinner;
	private EditText userNameEditText;
	private EditText passwEditText;
	private Button cancleButton;
	private Button okbButton;
	private TextView tipTextView;
	private CommunityList list=new CommunityList();
	private CommunityList buildList=new CommunityList();
	private final static int AFTER_INIT_COMMUNITY_LIST=1;
	private final static int EXCEPT_MSG=2;
	private final static int AFTER_SELECTED_COMMUNITY=3;
	private final static int AFTER_INIT_BUILD_LIST=4;
	private final static int SUCCESS_REGISTER=6;
	private final static int TIP_MSG=5;
	private String phoneNum;
	private Handler handler;
	private SimpleSpinnerAdapter commnuityAdapter;
	private SimpleSpinnerAdapter buildAdapter;
    private LoadingDialog loadingDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_community);
		phoneNum=getIntent().getStringExtra("phoneNum");
		initView();
	}
	/**
	 * 初始化界面控件
	 * */
	public void initView(){
		commnuitySpinner=(EditText) findViewById(R.id.register_spinner_comminuty);
		buildSpinner=(EditText) findViewById(R.id.register_spinner_build);
		userNameEditText=(EditText) findViewById(R.id.register_community_username);
		passwEditText=(EditText) findViewById(R.id.register_community_password);
		cancleButton=(Button) findViewById(R.id.register_community_cancle);
		okbButton=(Button) findViewById(R.id.register_community_ok);
		tipTextView=(TextView) findViewById(R.id.register_community_tipmsg);
		
		buildAdapter=new SimpleSpinnerAdapter(RegisterCommnuity.this,buildList.getList());
		okbButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                registerThread();
            }
        });
	}
	/**
	 * 线程注册
	 * */
	private void registerThread(){
        if(loadingDialog==null){
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.show();
        //首先检测用户名是否可用
        final String userNameTemp=userNameEditText.getText().toString();
        final String password=passwEditText.getText().toString();
        final Community communitySelect= (Community) commnuitySpinner.getTag();
        final Community buildSelect= (Community) buildSpinner.getTag();
        if(userNameTemp==null||userNameTemp.trim().equals("")) {
            tipTextView.setText("用户名不能为空");
            loadingDialog.dismiss();
            return ;
        }
        if(password==null||password.trim().equals("")) {
            tipTextView.setText("密码不能为空");
            loadingDialog.dismiss();
            return ;
        }
        if(communitySelect==null) {
            tipTextView.setText("小区不能为空");
            loadingDialog.dismiss();
            return ;
        }
//        if(buildSelect==null) {
//            tipTextView.setText("楼栋不能为空");
//            loadingDialog.dismiss();
//            return ;
//        }
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("username",userNameTemp);
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_REGISTER_CHECK_USERNAME,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                register(userNameTemp,password,phoneNum,communitySelect,buildSelect);
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                tipTextView.setText("用户名已存在,请更换用户名");
                loadingDialog.dismiss();
            }
        });
	}
    /**
     * 注册
     * */
    public void register(String userName,String passWord,String mobile,Community community,Community build){

        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("username", userName);
        requestParams.put("mobile", mobile);
        requestParams.put("password", passWord);
//        requestParams.put("buildingid", build.getId());
        requestParams.put("community_id", community.getId());
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_REGISTER,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                tipTextView.setText("注册成功");
                dialog();

                loadingDialog.dismiss();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                tipTextView.setText(arg3.getMessage());

                loadingDialog.dismiss();
            }
        });
    }
 	protected void dialog() {
	  AlertDialog.Builder builder = new Builder(RegisterCommnuity.this);
	  builder.setMessage("注册成功,点击确定返回！");
	  builder.setTitle("提示");
	  builder.setPositiveButton(R.string.text_queding, new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface arg0, int arg1) {
			// TODO Auto-generated method stub
			arg0.dismiss();
		    RegisterCommnuity.this.finish();
		}
	});
	  builder.create().show();
	 }
    /**
     * 显示小区选择框
     * */
    public void selectCommunity(View view){
        if(loadingDialog==null){
            loadingDialog=new LoadingDialog(this);
        }
        loadingDialog.show();
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("parentid",0);
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_GET_COMMINUTY_LIST,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                List<Community> communityList=CommunityList.parseList(responsePojo).getList();
                showDialogCommunity(communityList,commnuitySpinner);
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(RegisterCommnuity.this,"无法获取信息，请稍后再试",Toast.LENGTH_LONG).show();
                if(loadingDialog!=null&&loadingDialog.isShowing()){
                    loadingDialog.dismiss();
                }
            }
        });
    }
    /**
     * 显示楼栋选择框
     * */
    public void selectBuilder(View view){
        Community community= (Community) commnuitySpinner.getTag();
        if(community==null){
            Toast.makeText(this,"请先选择小区",Toast.LENGTH_LONG).show();
            return ;
        }

        if(loadingDialog==null){
            loadingDialog=new LoadingDialog(this);
        }
        loadingDialog.show();
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("parentid",community.getId());
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_GET_COMMINUTY_LIST,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                List<Community> communityList=CommunityList.parseList(responsePojo).getList();
                showDialogCommunity(communityList,buildSpinner);
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(RegisterCommnuity.this,"无法获取信息，请稍后再试",Toast.LENGTH_LONG).show();
                if(loadingDialog!=null&&loadingDialog.isShowing()){
                    loadingDialog.dismiss();
                }
            }
        });
    }
    /**
     * 弹出小区/楼栋选择框
     * */
     public void showDialogCommunity(final List<Community> communityList,final EditText editText){
         if(loadingDialog!=null&&loadingDialog.isShowing()){
             loadingDialog.dismiss();
         }
         final String[] items=fromList(communityList);
         if(items==null){
             Toast.makeText(this,"获取信息失败，请稍后重试!",Toast.LENGTH_SHORT).show();
             return ;
         }
         AlertDialog.Builder builder=new AlertDialog.Builder(this);
         builder.setTitle("请选择");
         builder.setItems(items,new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {
                 editText.setText(items[i]);
                 editText.setTag(communityList.get(i));
                 dialogInterface.dismiss();
             }
         });
         builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {
                 dialogInterface.dismiss();
             }
         });
         builder.show();
     }
    /**
     * 将小区列表转换成小区名称列表
     * */
    public String[] fromList(List<Community> communityList){
        if(communityList==null){
            return null;
        }
        String[] items=new String[communityList.size()];
        for(int i=0;i<communityList.size();i++){
            items[i]=communityList.get(i).getName();
        }
        return items;
    }
  }
